package com.luck.easyfoodbatch.ui;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.luck.easyfoodbatch.App;
import com.luck.easyfoodbatch.R;
import com.luck.easyfoodbatch.dialog.ShowProgressDialog;
import com.luck.easyfoodbatch.entity.User;
import com.luck.easyfoodbatch.preview.ImageInfo;
import com.luck.easyfoodbatch.swipbackhelper.SwipeBackHelper;
import com.luck.easyfoodbatch.swipbackhelper.SwipeListener;
import com.luck.easyfoodbatch.util.HttpUtil;
import com.luck.easyfoodbatch.util.T;
import com.luck.easyfoodbatch.util.ToolbarUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class BaseActivity extends AppCompatActivity {
    private final String TAG = "BaseActivity";
    protected Context mContext;
    // 页面无 Navigation 的模式
    public static final int MODE_NO_NAVIGATION = 0;
    // 页面有返回 Navigation 的模式
    public static final int MODE_BACK_NAVIGATION = 1;
    public static final int LOADING = 100;
    public static final int LOADING_SUCCESS = 200;
    public static final int LOADING_ERROR = 400;
    public static final int LOADING_SUCCESS_EMPTY = 800;
    protected ImageButton left_back;
    protected TextView tv_title;
    protected ImageView icon_right;
    protected TextView right_title;
    protected SharedPreferences sp;
    protected SharedPreferences.Editor edit;
    protected InputMethodManager manager;
    protected Handler mHandler = new Handler();
    public User user;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //StatusBarLightMode(this);
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentViewXml();
        user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
    }

    /**
     * 设置状态栏黑色字体图标，
     * 适配4.4以上版本MIUIV、Flyme和6.0以上版本其他Android
     *
     * @param activity
     * @return 1:MIUUI 2:Flyme 3:android6.0
     */
    public static int StatusBarLightMode(Activity activity) {
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (MiuiStatusBarDarkMode(activity, true)) {
                result = 1;
            } else if (FlymeSetStatusBarLightMode(activity, true)) {
                result = 2;
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                result = 3;
            }
        }
        return result;
    }

    /**
     * 设置状态栏图标为深色和魅族特定的文字风格
     * 可以用来判断是否为Flyme用户
     *
     * @param dark 是否把状态栏字体及图标颜色设置为深色
     * @return boolean 成功执行返回true
     */
    public static boolean FlymeSetStatusBarLightMode(Activity activity, boolean dark) {
        boolean result = false;
        try {
            WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
            Field darkFlag = WindowManager.LayoutParams.class
                    .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
            Field meizuFlags = WindowManager.LayoutParams.class
                    .getDeclaredField("meizuFlags");
            darkFlag.setAccessible(true);
            meizuFlags.setAccessible(true);
            int bit = darkFlag.getInt(null);
            int value = meizuFlags.getInt(lp);
            if (dark) {
                value |= bit;
            } else {
                value &= ~bit;
            }
            meizuFlags.setInt(lp, value);
            activity.getWindow().setAttributes(lp);
            result = true;
        } catch (Exception e) {

        }
        return result;
    }

    /**
     * 设置状态栏字体颜色
     *
     * @param activity
     * @param darkmode
     * @return
     */
    public static boolean MiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 向下展开动画
     *
     * @param view
     */
    public void startAnimation(View view, boolean isLocation) {
        if (isLocation) {
            //相对于自己的高度往下平移
            TranslateAnimation translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    -1.0f, Animation.RELATIVE_TO_SELF, 0.0f);
            translate.setDuration(100);//动画时间500毫秒
            translate.setFillAfter(true);//动画出来控件可以点击
            view.startAnimation(translate);//开始动画
            view.setVisibility(View.VISIBLE);//设置可见
        } else {
            //相对于自己的高度往上平移
            TranslateAnimation translate = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                    0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                    -1.0f);
            translate.setDuration(100);
            translate.setFillAfter(false);//设置动画结束后控件不可点击
            view.startAnimation(translate);
            view.setVisibility(View.GONE);//隐藏不占位置
        }
    }

    /**
     * 设置沉浸式状态栏
     */
    public void setPhoneStatus() {
        Window window = getWindow();
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.flags |= WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        window.setAttributes(layoutParams);
    }

    /**
     * 初始化加载过渡画面
     */
    protected void showLoadingView(int model) {
        final RelativeLayout rl_root = (RelativeLayout) findViewById(R.id.rl_root);
        final LinearLayout ll_error = (LinearLayout) findViewById(R.id.ll_error);
        final LinearLayout ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
        TextView retry_btn = (TextView) findViewById(R.id.retry_btn);
        retry_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                againBackClick();
            }
        });

        switch (model) {
            case LOADING:
                // 加载中
                rl_root.setVisibility(View.VISIBLE);
                ll_loading.setVisibility(View.VISIBLE);
                ll_error.setVisibility(View.GONE);
                break;
            case LOADING_SUCCESS:
                // 加载成功
                rl_root.setVisibility(View.GONE);
                ll_error.setVisibility(View.GONE);
                ll_loading.setVisibility(View.GONE);

                break;
            case LOADING_ERROR:
                // 延迟1秒 友好画面
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!isNetworkConnected()) {
                            // 加载失败
                            rl_root.setVisibility(View.VISIBLE);
                            ll_loading.setVisibility(View.GONE);
                            ll_error.setVisibility(View.VISIBLE);
                        }
                    }
                }, 1000);
                break;
        }
    }

    /**
     * 初始化加载过渡画面
     */
    protected void showLoadingView(final String msg, int model) {
        final RelativeLayout rl_root = (RelativeLayout) findViewById(R.id.rl_root);
        final LinearLayout ll_error = (LinearLayout) findViewById(R.id.ll_error);
        final LinearLayout ll_loading = (LinearLayout) findViewById(R.id.ll_loading);
        TextView retry_btn = (TextView) findViewById(R.id.retry_btn);
        final TextView description = (TextView) findViewById(R.id.description);
        retry_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                againBackClick();
            }
        });

        switch (model) {
            case LOADING:
                // 加载中
                rl_root.setVisibility(View.VISIBLE);
                ll_loading.setVisibility(View.VISIBLE);
                ll_error.setVisibility(View.GONE);
                break;
            case LOADING_SUCCESS:
                // 加载成功
                rl_root.setVisibility(View.GONE);
                ll_error.setVisibility(View.GONE);
                ll_loading.setVisibility(View.GONE);
                break;
            case LOADING_SUCCESS_EMPTY:
                // 加载成功 但无数据 适用无列表数据
                // 延迟1秒 友好画面
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        rl_root.setVisibility(View.VISIBLE);
                        ll_error.setVisibility(View.VISIBLE);
                        ll_loading.setVisibility(View.GONE);
                        description.setText(msg);
                    }
                }, 800);
                break;
            case LOADING_ERROR:
                // 延迟1秒 友好画面
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (!isNetworkConnected()) {
                            // 加载失败
                            rl_root.setVisibility(View.VISIBLE);
                            ll_loading.setVisibility(View.GONE);
                            ll_error.setVisibility(View.VISIBLE);
                        }
                    }
                }, 800);
                break;
        }
    }


    /**
     * 初始化菜单栏
     */
    protected void initTitleBar(String title, String rightText, int pageMODE) {
        ImageButton left_back = (ImageButton) findViewById(R.id.left_back);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        TextView right_title = (TextView) findViewById(R.id.right_title);
        tv_title.setText(title);
        right_title.setText(rightText);
        right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rightClick();
            }
        });
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                left_back.setVisibility(View.GONE);
                break;

            case MODE_BACK_NAVIGATION:
                left_back.setVisibility(View.VISIBLE);
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
        }
    }

    /**
     * 初始化菜单栏
     */
    protected void initTitleBar(int titleId, int rightTextId, int pageMODE) {
        ImageButton left_back = (ImageButton) findViewById(R.id.left_back);
        TextView tv_title = (TextView) findViewById(R.id.tv_title);
        TextView right_title = (TextView) findViewById(R.id.right_title);
        tv_title.setText(titleId);
        right_title.setText(rightTextId);
        right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rightClick();
            }
        });
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                left_back.setVisibility(View.GONE);
                break;

            case MODE_BACK_NAVIGATION:
                left_back.setVisibility(View.VISIBLE);
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
        }
    }

    /**
     * @return void 返回类型
     * @Title: rightClick
     * @Description: 右边的按下
     * @author luck
     */
    public void rightClick() {

    }


    /**
     * @return void 返回类型
     * @Title: backClick
     * @Description: 返回键
     * @author luck
     */
    public void backClick() {
        finish();
    }

    /**
     * @return void 返回类型
     * @Title: backClick
     * @Description: 返回键
     * @author luck
     */
    public void againBackClick() {

    }

    // 布局数据初始化
    protected void setContentViewXml() {
        mContext = this;
        manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        edit = sp.edit();
        SwipeBackHelper.onCreate(this);
        SwipeBackHelper.getCurrentPage(this)
                .setSwipeBackEnable(true)//设置是否可滑动
                .setSwipeSensitivity(0.5f)//对横向滑动手势的敏感程度。0为迟钝 1为敏感
                .setSwipeRelateEnable(true)//是否与下一级activity联动(微信效果)。默认关
                .setSwipeEdgePercent(0.1f)//可滑动的范围。百分比。0.2表示为左边20%的屏幕
                .setSwipeRelateOffset(300).addListener(new SwipeListener() {//滑动监听
            @Override
            public void onScroll(float percent, int px) {//滑动的百分比与距离
            }

            @Override
            public void onEdgeTouch() {//当开始滑动
            }

            @Override
            public void onScrollToClose() {//当滑动关闭
            }
        });
    }

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
    }


    // 重载 setContentView
    public void setContentView(@LayoutRes int layoutResID, int resTitleID, int pageMODE) {
        super.setContentView(layoutResID);
        left_back = $(R.id.left_back);
        tv_title = $(R.id.tv_title);
        right_title = $(R.id.right_title);
        tv_title.setText(resTitleID);
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                break;

            case MODE_BACK_NAVIGATION:
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
            // 其它
        }
    }

    // 重载 setContentView
    public void setContentView(@LayoutRes int layoutResID, String title, int resId, int pageMODE) {
        super.setContentView(layoutResID);
        // setToolbarStatus();
        left_back = $(R.id.left_back);
        tv_title = $(R.id.tv_title);
        icon_right = $(R.id.icon_right);
        tv_title.setText(title);
        icon_right.setImageResource(resId);
        icon_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rightClick();
            }
        });
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                break;

            case MODE_BACK_NAVIGATION:
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
            // 其它
        }
    }

    // 重载 setContentView
    public void setContentView(@LayoutRes int layoutResID, String title, int pageMODE) {
        super.setContentView(layoutResID);
        // setToolbarStatus();
        left_back = $(R.id.left_back);
        tv_title = $(R.id.tv_title);
        right_title = $(R.id.right_title);
        tv_title.setText(title);
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                break;

            case MODE_BACK_NAVIGATION:
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
            // 其它
        }
    }

    // 重载 setContentView
    public void setContentView(@LayoutRes int layoutResID, int resTitleID, String rightTitle, int pageMODE) {
        super.setContentView(layoutResID);
        // setToolbarStatus();
        left_back = $(R.id.left_back);
        tv_title = $(R.id.tv_title);
        right_title = $(R.id.right_title);
        tv_title.setText(resTitleID);
        right_title.setText(rightTitle);
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                break;

            case MODE_BACK_NAVIGATION:
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
            // 其它
        }
    }


    // 重载 setContentView
    public void setContentView(@LayoutRes int layoutResID, String title, String rightTitle, int pageMODE) {
        super.setContentView(layoutResID);
        // setToolbarStatus();
        left_back = $(R.id.left_back);
        tv_title = $(R.id.tv_title);
        right_title = $(R.id.right_title);
        tv_title.setText(title);
        right_title.setText(rightTitle);
        right_title.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                rightClick();
            }
        });
        switch (pageMODE) {
            case MODE_NO_NAVIGATION:
                // 页面没有返回箭头
                break;

            case MODE_BACK_NAVIGATION:
                // 页面有返回剪头
                left_back.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        backClick();
                    }
                });
                break;
            // 其它
        }
    }


    // 设置状态栏颜色
    protected void setToolbarStatus() {
        ToolbarUtil.setColor(this, getResources().getColor(R.color.colorPrimaryDark));
    }

    @SuppressWarnings("unchecked")
    public <T> T $(int resID) {
        return (T) findViewById(resID);
    }

    protected void showToast(String msg) {
        Toast.makeText(BaseActivity.this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 防止连续点击跳转两个页面
     */
    protected long lastClickTime;

    protected boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 900) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * @param clz
     * @return void 返回类型
     * @Title: startActivity
     * @Description: 进入到下个activity
     * @author luck
     */
    protected void startAct(Class clz) {
        if (isFastDoubleClick()) {
            return;
        }
        Intent intent = new Intent(mContext, clz);
        startActivity(intent);
    }

    /**
     * @param clz
     * @return void 返回类型
     * @Title: startActivity
     * @Description: 进入到下个activity
     * @author luck
     */
    protected void startAct(Class clz, Bundle bundle) {
        if (isFastDoubleClick()) {
            return;
        }
        Intent intent = new Intent(this, clz);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * @param clz
     * @return void 返回类型
     * @Title: startActivity
     * @Description: 进入到下个activity, 并关闭当前Activity
     * @author luck
     */
    protected void startFinishAct(Class clz, Bundle bundle) {
        if (isFastDoubleClick()) {
            return;
        }
        Intent intent = new Intent(this, clz);
        intent.putExtras(bundle);
        startActivity(intent);
        finish();
    }


    /**
     * 隐藏软键盘
     */
    protected void hideKeyboard(EditText editText) {
        InputMethodManager inputMethodManager =
                (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }

    /**
     * 显示软键盘
     */
    protected void showKeyboard(EditText editText) {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                manager.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
        }
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    protected boolean isCheckedLogin() {
        User user = (User) App.getInstance().readObject(HttpUtil.USER_KEY);
        if (user == null || TextUtils.isEmpty(user.getUid() + "")) {
            return false;
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SwipeBackHelper.onDestroy(this);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        SwipeBackHelper.onPostCreate(this);
    }

    /**
     * 获得状态栏的高度
     */
    protected int getStatusHeight(Context context) {
        int statusHeight = -1;
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$dimen");
            Object object = clazz.newInstance();
            int height = Integer.parseInt(clazz.getField("status_bar_height").get(object).toString());
            statusHeight = context.getResources().getDimensionPixelSize(height);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return statusHeight;
    }

    /**
     * 查看图片 初始化启动动画参数
     * 单张图片
     */
    protected List<ImageInfo> initAnimImage(ImageView view, String path) {
        List<ImageInfo> list = new ArrayList<>();
        list.clear();
        ImageInfo info = new ImageInfo();
        info.imageViewWidth = view.getWidth();
        info.imageViewHeight = view.getHeight();
        info.setThumbnailUrl(path);// 缩略图地址
        info.setBigImageUrl(path);// 原图地址
        // 图片所在位置的x y 坐标
        int[] points = new int[2];
        view.getLocationInWindow(points);
        info.imageViewX = points[0];
        info.imageViewY = points[1] - getStatusHeight(mContext);
        list.add(info);
        return list;
    }

    /**
     * 广播发送者
     *
     * @param action
     */
    protected void sendBroadcast(String action) {
        Intent intent = new Intent();
        intent.setAction(action);
        sendBroadcast(intent);
    }


    /**
     * 注册发送者
     *
     * @param action
     */
    protected void registerReceiver(BroadcastReceiver receiver, String... action) {
        IntentFilter intentFilter = new IntentFilter();
        for (int i = 0; i < action.length; i++) {
            intentFilter.addAction(action[i]);
        }
        registerReceiver(receiver, intentFilter);
    }

    /**
     * 检测网络是否可用
     *
     * @return
     */
    public boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        return ni != null && ni.isConnectedOrConnecting();
    }

    /**
     * 加载提示
     */
    private ShowProgressDialog dialog;

    protected void showProgressDialog(String msg) {
        dialog = new ShowProgressDialog(this);
        dialog.setContent(msg);
        if (!isFinishing()) {
            dialog.show();
        }
    }


    protected void hideShowProgress() {
        if (dialog != null && dialog.isShowing()) {
            if (!isFinishing()) {
                dialog.dismiss();
            }
        }
    }
}
